/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package escom.ipn.Acceso;

import escom.ipn.modelo.delegate.UsuarioDelegate;
import escom.ipn.modelo.delegate.UsuarioIncidenteDelegate;
import escom.ipn.modelo.delegate.adminSectorDelegate;
import escom.ipn.modelo.dto.SectorClass;
import escom.ipn.modelo.dto.Usuario;
import escom.ipn.modelo.dto.UsuarioIncidente;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Daniel
 */
public class login extends HttpServlet {

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            /*
             * TODO output your page here. You may use following sample code.
             */
                String usuario, password, html, msg;
                
                UsuarioIncidenteDelegate uidel = new UsuarioIncidenteDelegate();
                
                UsuarioDelegate del = new UsuarioDelegate();
                UsuarioDelegate del2 = new UsuarioDelegate();
                Usuario a = new Usuario();
                
                a.setUsuario(request.getParameter("Usuario"));
                a.setPassword(request.getParameter("Password"));

                try {                
                    a=del.mostrarUsuario(a);
                    html = "Exito";

                    if(a != null){ 
                        HttpSession sess = request.getSession(true);

                        a.setCAT_ESTADO_USUARIO_id_estado_usuario(2);
                        del2.CambiarEstado(a);

                        synchronized (sess) {                    
                            sess.setAttribute("idTipoUsuario", a.getTipoUsuario());                    
                            sess.setAttribute("Usuario", a.getUsuario());
                            sess.setAttribute("Nombre",a.getNombre());
                            sess.setAttribute("sector",a.getSector());
                            sess.setAttribute("id_Usuario",a.getId());
                            SectorClass sec = new  SectorClass();
                            adminSectorDelegate secd = new adminSectorDelegate();
                            sec.setId(a.getSector());
                            List nomSector = secd.getSectorNOMBRE(sec);
                            sec = (SectorClass) nomSector.get(0);
                            sess.setAttribute("nombresector", sec.getNombre());
                        }
                        if(sess.getAttribute("idTipoUsuario").equals("1")){                        
                            sess.setAttribute("tipoUsuario", "Operador");
                            response.sendRedirect("Operador/operador.jsp");
                        }
                        if(sess.getAttribute("idTipoUsuario").equals("2")){                        
                            sess.setAttribute("tipoUsuario", "Despachador");
                            List noasignados = uidel.mostrarNoAsignados(Integer.parseInt(sess.getAttribute("sector").toString()));
                            if(noasignados!=null){
                                for(int i=0;i<noasignados.size();i++){
                                    UsuarioIncidente ui = (UsuarioIncidente)noasignados.get(i);
                                    ui.setIncidenteId(ui.getIncidenteId());
                                    ui.setUsuarioId(Integer.parseInt(sess.getAttribute("id_Usuario").toString()));
                                    UsuarioIncidenteDelegate uid =new UsuarioIncidenteDelegate();
                                    uid.crear(ui);
                                }
                            }
                            response.sendRedirect("Despachador/despachador.jsp");

                        }
                        if(sess.getAttribute("idTipoUsuario").equals("3")){                        
                            sess.setAttribute("tipoUsuario", "Administrador");
                            response.sendRedirect("Administrador/administrador.jsp");

                        }

                    }
                    else{
                        response.sendRedirect("errorlogin.jsp");
                    }

                } catch (SQLException ex) {
                    html = "Fracaso";
                    Logger.getLogger(login.class.getName()).log(Level.SEVERE, null, ex);                
                }
            
                response.setContentType("text/html");
                out = response.getWriter();
                out.println(html);
        } finally {            
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
